<?php
class mod_user extends core_modbase {

	protected $auth;
	protected $session;
	protected $user;
	
	public function __construct()
	{
		parent::__construct();
		$this->auth = new auth();
		$this->session = new session();
		$this->user = new user();
	}
	
	public function PAGE_inscription ($etape = 'log_info')
	{
		$this->translator->load('inscription');
		$captcha = new Captcha();
		$auth_form = $this->auth->InscriptionForm($this->translator);
		$user_form = $this->user->InscriptionForm($this->translator);

		if ($_SERVER['REQUEST_METHOD'] == 'POST')
		{
			try 
			{
				if ($auth_form->valid($_POST) && $user_form->valid($_POST) && $captcha->verify($_POST['code']))
				{
					$user_id = $this->user->create($_POST);
					$this->auth->create($user_id, $_POST);
					$this->session->set('registred_user', $user_id);
					$this->assign('message', 'inscrit');
					$this->display('message.html');
					return;
				}
			}
			catch (FormValidateError $e)
			{
				$this->template->assign('message', $e->getMessage());
			}
		}
		
		$this->template->assign('auth_form', $auth_form->Generate($_POST));
		$this->template->assign('detail_form', $user_form->Generate($_POST));
		$this->template->assign('CAPTCHA', $captcha->display());
		$this->display('inscription.html');
	}
	
	public function PAGE_deconnexion ()
	{
		$this->assign('message', 'logout');
		$this->session->delete('registred_user');
		$this->display('message.html');
	}
	
	public function PAGE_connexion ()
	{
		if ($this->user->isRegistred())
		{
			$this->assign('message', 'already_connected');
			$this->display('message.html');
		}
		elseif ($this->auth->isPosted())
		{
			try {
				$user_id = $this->auth->Connect();
				$this->session->set('registred_user', $user_id);
				$this->assign('message', 'connected');
				$this->display('message.html');
			}
			catch (LoginError $e)
			{
				$this->assign('message', 'mdperror');
				$this->template->assign('connectform', $this->auth->GetForm());
				$this->display('connexion.html');
			}
		}
		else
		{
			$this->template->assign('connectform', $this->auth->GetForm());
			$this->display('connexion.html');
		}
	}

}
